package zy.blue7.im.core.service.impl;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import zy.blue7.im.common.message.LoginMessage;
import zy.blue7.im.common.message.Message;
import zy.blue7.im.common.message.response.Result;
import zy.blue7.im.core.other.Container;
import zy.blue7.im.core.service.MessageHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: blue7
 * @Date: 2022/2/27 20:05
 * @Version 1.0
 * @Description
 */
public class LoginMessageHandlerImpl implements MessageHandler {
    @Override
    public void handle(Message message, Channel channel) throws IOException {
        /**
         * 登录就把 当前 channel 放到 容器中
         */
        LoginMessage loginMessage = (LoginMessage) message;
        String username = loginMessage.getUsername();
        String password = loginMessage.getPassword();
        /**
         * 按道理这里会从数据库查询用户名和密码，如果不满足就拒绝登录
         */
        if (null == username || password == null) {
            Result<Boolean> result = Result.failed("用户名或者密码错误...", false);
            /**
             * 登录失败就发送失败消息
             */
            ChannelFuture channelFuture = channel.writeAndFlush(result);
            /**
             * 添加监听器，不管发送成功还是失败， todo 暂时全部直接关闭channel
             */
            channelFuture.addListener(future -> {
//                if (future.isSuccess())
                channel.close();
            });
            System.out.println("登录失败");

        } else {
            /**
             * 如果登录成功，就 将 该channel 放到容器中
             */
            Container.map.put(loginMessage.getFrom(), channel);
            /**
             * 暂时先把 所有人都放到一个组中,
             * todo 正常情况下 应该从数据库查询关系，然后将channel 放在 指定的组内
             */
            List<Channel> list = Container.groupMap.get("group1");
            if (null == list || list.isEmpty()) {
                List<Channel> list1 = new ArrayList<>();
                list1.add(channel);
                Container.groupMap.put("group1", list1);
            } else {
                Container.groupMap.get("group1").add(channel);
            }

            Result<Boolean> result = Result.success(true, "登录成功...");
            sendMessage(result, channel);
        }
        System.out.println(loginMessage + "----------");
    }
}
